import { defineStore } from 'pinia';
import type { RouteLocationNormalizedLoaded } from 'vue-router';

interface Route {
    level1: string;
    level2: string;
    title: string;
}

interface User {
    id:string,
    account: string;
    name: string;
    nickname: string;
    avatar: string;
    phone: string;
    email: string;
    roleCodeList: string[];
    permissionCodeList: string[];
}

const useApp = defineStore('app', {
    state: () => {
        return {
            route: {
                level1: '',
                level2: '',
                title: '',
            } as Route,
            user: {
                id:'',
                account: '',
                name: '',
                nickname: '',
                avatar: '',
                phone: '',
                email: '',
                roleCodeList: [],
                permissionCodeList: [],
            } as User,
        };
    },
    getters: {
        routeLevel1: (state) => state.route.level1,
        routeLevel2: (state) => state.route.level2,
        routeTitle: (state) => state.route.title,
        loginUser: (state) => {
            const id = state.user.id || state.user.id || '';
            const name = state.user.nickname || state.user.account || '';
            const roleName = state.user.name || state.user.roleCodeList[0] || '';
            const avatar = state.user.avatar || '';
            return {
                id,
                name,
                roleName,
                avatar,
            };
        },
    },
    actions: {
        setRoute(data: RouteLocationNormalizedLoaded) {
            if (data.matched[1]) {
                this.route.level1 = data.matched[1].name as string;
            } else {
                this.route.level1 = '';
            }
            if (data.matched[2]) {
                this.route.level2 = data.matched[2].name as string;
            } else {
                this.route.level2 = '';
            }
            this.route.title = data?.meta?.title || (data.name as string) || '';
        },
        setUser(data: any) {
            const userInfo: any = { ...this.user };
            for (let key in userInfo) {
                if (data[key]) {
                    userInfo[key] = data[key];
                }
            }
            this.user = userInfo;
        },
    },
});

export default useApp;
